package com.example.demo.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class FileController {

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

    @PostMapping("upload")
    public String upload(@RequestParam(value = "uploadFile", required = false) MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        String realPath = "C:/uploadFile/";
        String format = simpleDateFormat.format(new Date());
        File folder = new File(realPath + format);
        if (!folder.isDirectory()) {
            folder.mkdir();
        }
        String fileName = multipartFile.getOriginalFilename();
        multipartFile.transferTo(new File(folder, fileName));
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" + format + "/" + fileName;
    }

}
